<template>
    <el-form ref="formRef" :model="formData" :inline="true" label-width="120px" status-icon>
        <el-form-item label="供应商">
            <el-select v-model="formData.vendorId" placeholder="请选择供应商">
                <el-option v-for="item in vendorData" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="采购日期">
            <el-date-picker v-model="formData.poDate" type="date" placeholder="请选择"/>
        </el-form-item>
        <el-form-item label="总价">
            <el-input v-model="formData.sum" disabled>
                <template #prepend>¥</template>
            </el-input>
        </el-form-item>
        <el-form-item label="备注">
            <el-input v-model="formData.brief" :rows="1" type="textarea" placeholder="备注"/>
        </el-form-item>
    </el-form>
  <!--分割线-->
    <el-divider/>
  <!--调出抽屉按钮-->
    <el-button type="primary" @click="drawer = true">
        选择商品
    </el-button>
    <el-divider/>

  <!--采购单表格-->
    <el-table :data="tableData" border style="width: auto" ref="productTableRef">
        <el-table-column fixed prop="productId" label="商品编号" min-width="90"/>
        <el-table-column fixed prop="productName" label="商品名称" min-width="250"/>
        <el-table-column prop="img" label="图片" min-width="70">
            <template #default="scope">
                <img :src="scope.row.img.split(',')[0]" width="50" height="50"/>
            </template>
        </el-table-column>
        <el-table-column prop="qty" label="数量" min-width="150">
            <template #default="scope">
                <el-input-number v-model="scope.row.qty" :min="1" :max="99999" @change="change(scope)" size="small"/>
            </template>
        </el-table-column>

        <el-table-column prop="price" label="单价" min-width="150">
            <template #default="scope">
                <el-input-number v-model="scope.row.price" @change="change(scope)" :precision="2" :step="0.1" :min="1"
                                 :max="99999" size="small"/>
            </template>
        </el-table-column>

        <el-table-column prop="totalPrice" label="合计" min-width="100">
            <template #default="scope">
                ￥ {{ scope.row.totalPrice }}
            </template>

        </el-table-column>
        <el-table-column prop="brief" label="备注" min-width="120">
            <template #default="scope">
                <el-input v-model="scope.row.brief" size="small"/>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120" align="center">
            <template #default="scope">
                <el-button type="primary" size="small" @click="deleteRow(scope)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <el-divider/>
    <el-button type="primary" @click="submitForm">
        保存采购单
    </el-button>

    <el-drawer v-model="drawer" direction="ltr" size="50%">
        <ProductPickVue v-model="selectProducts"></ProductPickVue>
    </el-drawer>
</template>


<script setup lang="ts">
import {ref, onMounted, reactive, watch} from 'vue'
import {ElMessage, dayjs} from 'element-plus'
import {poApi, vendorApi} from '@/api'
import ProductPickVue from '@/components/ProductPick.vue'
import {useRouter} from 'vue-router'
import {storeToRefs} from 'pinia'
import appStore from "@/store/appStore.ts";

const {po_item_data} = storeToRefs(appStore())
const selectProducts = ref([])
const router = useRouter()

const tableData: any = ref([])
const vendorData = ref([])
const formData = reactive({
    vendorId: '',
    poDate: dayjs().add(1, 'day').format('YYYY-MM-DD'),
    sum: 0,
    brief: ""
})
const drawer = ref(false)
onMounted(() => {
    callVendorApi()
    tableData.value = po_item_data.value
    computeSumPrice()
})

const deleteRow = (scope: any) => {
    tableData.value.splice(scope.$index, 1)
}

const computeSumPrice = () => {
    let sum = 0
    tableData.value.forEach((item: any) => {
        sum += item.totalPrice
    })
    formData.sum = Number(sum.toFixed(2))
}

const change = (param: any) => {
    let index = param.$index;
    let currProduct = tableData.value[index]
    currProduct.totalPrice = Number((currProduct.qty * currProduct.price).toFixed(2))
    computeSumPrice()
}


watch(() => selectProducts.value, (newProduct, oldProduct) => {
    drawer.value = false
    newProduct.forEach((item: any) => {
        let existProduct = tableData.value.filter((p: any) => p.productId === item.id);
        if (existProduct.length == 0) {
            tableData.value.push({
                productId: item.id,
                productName: item.name,
                img: item.img,
                qty: 1,
                price: item.price,
                totalPrice: item.price,
                brief: ""
            })
        }
    })
    computeSumPrice()
    po_item_data.value = tableData.value
})


const callVendorApi = () => {
    //没有禁用的供应商
    vendorApi.select.call({status: 1}).then((res: any) => {
        vendorData.value = res
    })
}


const formSubmit = () => {
    if (formData.vendorId === "") {
        ElMessage.error("请选择供应商")
        return
    }
    let poMaster = {
        vendorId: formData.vendorId,
        vendorName: vendorData.value.filter((p: any) => p.id === formData.vendorId)[0].name,
        poDate: formData.poDate,
        totalPrice: formData.sum,
        brief: formData.brief,
        items: tableData.value
    }
    //保存单据
    poApi.insert.call(poMaster).then((res: any) => {
        ElMessage.success("保存成功")
        tableData.value = []
        po_item_data.value = []
    })
}

const submitForm = () => {
    if (tableData.value.length === 0) {
        ElMessage.error("至少选择一个商品")
        return
    }
    formSubmit()
}
</script>